<template>
  <Dialog
    :title="dialogType == 'add' ? '新增' : '修改'"
    :visible="visible"
    @cancel="handleCancel"
    @success="handleSuccess"
  >
    <el-form
      slot="content"
      ref="userForm"
      :model="userForm"
      :rules="rules"
      :status-icon="true"
      label-width="100px"
      label-position="right"
    >
      <el-form-item label="用户名：" prop="userName">
        <el-input v-model="userForm.userName" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="姓：">
        <el-input v-model="userForm.surname" placeholder="请输入姓" />
      </el-form-item>
      <el-form-item label="名：">
        <el-input v-model="userForm.name" placeholder="请输入名" />
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input
          v-model="userForm.password"
          show-password
          placeholder="请输入密码"
        />
      </el-form-item>
      <el-form-item label="确认密码：" prop="confirmPassword">
        <el-input
          v-model="userForm.confirmPassword"
          show-password
          placeholder="请再次输入密码"
        />
      </el-form-item>
      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="userForm.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="手机号：">
        <el-input v-model="userForm.phoneNumber" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="userForm.lockoutEnabled">
          登录失败,账户被锁定
        </el-checkbox>
      </el-form-item>
      <el-form-item label="角色：">
        <el-checkbox-group v-model="userForm.roleNames">
          <el-checkbox
            v-for="item in assignableRoles"
            :key="item.id"
            :label="item.name"
          />
        </el-checkbox-group>
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script>
import Dialog from '@/components/Dialog'
import { assignableRoles, getUserPermission } from '@/http/modules/user'
import { validPassword } from '@/utils'
export default {
  components: { Dialog },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    dialogType: {
      type: String,
      default: 'add'
    }
  },
  data() {
    var validPassWords = (rule, value, callback) => {
      const vm = this
      if (vm.dialogType === 'edit' && value === '') {
        callback()
        return
      }
      if (!validPassword(value)) {
        callback(
          new Error('密码必须包含大小写字母、数字和特殊字符（长度大于6位）！')
        )
      }
      callback()
    }
    var validConfirmPassword = (rule, value, callback) => {
      const vm = this
      if (vm.dialogType === 'edit' && value === '') {
        callback()
        return
      }
      if (!validPassword(value)) {
        callback(
          new Error('密码必须包含大小写字母、数字和特殊字符（长度大于6位）！')
        )
      }
      if (vm.userForm.confirmPassword !== vm.userForm.password) {
        callback(new Error('请确认两次密码一致！'))
      }
      callback()
    }
    return {
      userForm: {
        userName: '',
        surname: '',
        name: '',
        password: '',
        confirmPassword: '',
        email: '',
        phoneNumber: '',
        lockoutEnabled: true,
        roleNames: []
      },
      addRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validPassWords, trigger: 'blur' }
        ],
        confirmPassword: [
          {
            required: true,
            message: '请再次输入密码',
            trigger: 'blur'
          },
          { validator: validConfirmPassword, trigger: 'blur' }
        ],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }]
      },
      editRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [{ validator: validPassWords, trigger: 'blur' }],
        confirmPassword: [{ validator: validConfirmPassword, trigger: 'blur' }],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }]
      },
      assignableRoles: [],
      editId: ''
    }
  },
  computed: {
    rules() {
      const vm = this
      if (vm.dialogType === 'add') {
        return vm.addRules
      }
      return vm.editRules
    }
  },
  mounted() {
    const vm = this
    vm.getassignableRoles()
  },
  methods: {
    handleCancel() {
      const vm = this
      vm.$emit('cancel')
    },
    handleSuccess() {
      const vm = this
      vm.validateForm()
        .then(() => {
          vm.$emit('success', vm.userForm)
        })
        .catch(err => {
          console.log(err)
        })
    },
    async getassignableRoles() {
      const vm = this
      const res = await assignableRoles()
      vm.assignableRoles = res.items
    },
    validateForm() {
      const vm = this
      return new Promise((resolve, reject) => {
        vm.$refs.userForm.validate(valid => {
          if (valid) {
            resolve()
          } else {
            reject()
            return false
          }
        })
      })
    },
    async setData(row) {
      const vm = this
      vm.editId = row.id
      await vm.getassignableRoles()
      const { items } = await vm.getUserPermission(vm.editId)
      vm.userForm = {
        userName: row.userName,
        concurrencyStamp: row.concurrencyStamp,
        surname: row.surname,
        name: row.name,
        password: '',
        confirmPassword: '',
        email: row.email,
        phoneNumber: row.phoneNumber,
        lockoutEnabled: row.lockoutEnabled,
        roleNames: items.map(e => e.name)
      }
    },
    resetForm() {
      const vm = this
      vm.$refs.userForm.resetFields()
    },
    async getUserPermission(id) {
      const res = await getUserPermission(id)
      return res
    }
  }
}
</script>

<style lang="scss" scoped></style>
